<template>
  <div class="app-container flex flex-direction flex-sub"
    style="background: none; height: 100%; padding: 1rem">
    <el-card shadow="never"
      class="box-card flex-sub"
      style="overflow: auto">
      <div class="div-query">
        <div class="collapse">
          <div class="collapse-header"
            @click="panelActive = !panelActive">
            <i class="collapse-header-icon"
              :class="[
                panelActive ? 'el-icon-caret-bottom' : 'el-icon-caret-top',
              ]" />
            {{ panelActive ? '隐藏' : '展开' }}查询条件
          </div>
          <div class="collapse-content">
            <el-collapse-transition>
              <div v-show="panelActive">
                <el-form size="small"
                  label-position="right">
                  <el-row>
                    <el-col :span="8">
                      <el-form-item label="设备区分"
                        label-width="80px">
                        <el-select v-model="searchModel.deviceIsLine"
                          popper-class="global-select"
                          placeholder="选择设备区分"
                          clearable
                          filterable>
                          <el-option v-for="item in deviceIsLineList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                        </el-select>
                      </el-form-item>
                    </el-col>

                    <el-col :span="8">
                      <el-form-item label="设备编码"
                        label-width="80px">
                        <el-input v-model="searchModel.deviceSource"
                          placeholder="设备编码"
                          clearable
                          class="filter-item search-item" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="设备名称"
                        label-width="80px">
                        <el-input v-model="searchModel.deviceName"
                          placeholder="设备名称"
                          clearable
                          class="filter-item search-item" />
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="8">
                      <el-form-item label="告警类型"
                        label-width="80px">
                        <el-select v-model="searchModel.deviceStatus"
                          popper-class="global-select"
                          placeholder="选择设备告警类型"
                          clearable
                          filterable>
                          <el-option v-for="item in deviceStatusList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="告警状态"
                        label-width="80px">
                        <el-select v-model="searchModel.solveStatus"
                          placeholder="选择设备告警状态"
                          clearable
                          filterable>
                          <el-option v-for="item in solveStatusList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="告警地点"
                        label-width="80px">
                        <el-input v-model="searchModel.deviceAddress"
                          placeholder="告警地点"
                          clearable
                          class="filter-item search-item" />
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="8">
                      <el-form-item label="告警时间"
                        label-width="80px">
                        <el-date-picker v-model="value2"
                          type="datetimerange"
                          :picker-options="warningOptions"
                          range-separator="至"
                          start-placeholder="告警开始时间"
                          end-placeholder="告警结束时间"
                          align="right"
                          @change="handleDateChange" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="工单状态"
                        label-width="80px">
                        <el-select v-model="searchModel.jobStatus"
                          placeholder="选择工单状态"
                          clearable
                          filterable>
                          <el-option v-for="item in jobStatusList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item style="margin-left: 10px">
                        <el-button type="primary"
                          icon="el-icon-search"
                          @click="toSearch"
                          size="small"
                          style="margin-right: 10px">搜索</el-button>
                        <el-button icon="el-icon-delete"
                          @click="toReset"
                          type="info"
                          size="small"
                          style="margin-right: 10px">重置</el-button>

                        <el-button size="small"
                          @click="getDataList(true)">
                          <i class="el-icon-refresh"
                            style="color: #606266" />
                          <span style="color: #606266">刷新</span>
                        </el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </el-collapse-transition>
          </div>
        </div>
      </div>

      <div>
        <div v-if="selectedDataList.length != 0"
          class="alert-div">
          <i class="el-icon-info"
            style="color: #1890ff; margin-right: 3px" />
          已选择
          <strong style="color: #1890ff; margin: 0px 1px; font-size: 15px">
            {{ selectedDataList.length }}
          </strong>
          项
          <el-button type="text"
            style="padding: 10px"
            @click="toEmptySelection">
            清空
          </el-button>
        </div>

        <!-- <el-popover v-model="popoverVisible" placement="top" trigger="manual"> -->
        <!-- <i class="el-icon-question"
             style="color: rgb(255, 153, 0)" />
          <span>
            确定要删除已选的
            <strong style="color: #1890ff; margin: 0px 1px">
              {{ selectedDataList.length }}
            </strong>
            项数据吗？
          </span>
          <div style="text-align: right; margin-top: 10px">
            <el-button size="mini"
                       type="text"
                       @click="popoverVisible = false">取消</el-button>
            <el-button type="primary"
                       size="mini"
                       @click="toBatchDeleteConfirm">确定</el-button>
          </div> -->
        <el-button @click="batchEliminate"
          size="small"
          style="margin-bottom: 8px; margin-right: 10px"
          type="danger">
          <!-- <i class="iconfont icon-xiaochujingbao" style="font-size: 10px" /> -->
          <img :src="eliminateIcon1"
            style="
                position: relative;
                width: 12px;
                height: 12px;
                top: 1px;
                margin-right: 1px;
              " />
          批量消警
        </el-button>
        <el-button icon="el-icon-check"
          @click="batchComfirm"
          size="small"
          type="primary"
          style="margin-right: 10px">
          批量确认
        </el-button>
        <el-button icon="el-icon-s-promotion"
          @click="batchDistribution"
          size="small"
          type="success">
          批量派发
        </el-button>

        <el-table ref="elTable"
          size="medium"
          v-loading="loading || deleteLoading"
          border
          fit
          :data="dataList"
          :row-key="(row) => row.id"
          style="width: 100%"
          @sort-change="onSortChange"
          @selection-change="onSelectionChange"
          :header-cell-style="{ background: '#fafafa' }">
          <af-table-column align="center"
            type="selection"
            width="40"
            fixed
            :reserve-selection="true"
            :selectable="isChecked" />
          <el-table-column align="center"
            type="index"
            width="50"
            fixed
            label="#"
            :index="indexMethod" />
          <af-table-column align="center"
            label="设备区分">
            <template slot-scope="{ row }">
              {{ row.deviceIsLine == 0 ? '传统有线' : '智能无线' }}
            </template>
          </af-table-column>
          <af-table-column align="center"
            label="设备类型"
            prop="deviceTypeStr">
          </af-table-column>
          <af-table-column align="center"
            label="设备编码"
            prop="deviceSource" />
          <af-table-column align="center"
            label="设备名称"
            prop="deviceName" />
          <af-table-column align="center"
            label="告警时间"
            prop="alertTime">
            <template slot-scope="{ row }">
              {{ row.alertTime | datefmt('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </af-table-column>
          <af-table-column align="center"
            label="告警地点"
            prop="deviceAddress" />
          <af-table-column align="center"
            label="告警原因"
            prop="alarmCause" />
          <af-table-column align="center"
            label="告警类型"
            prop="deviceStatus">
            <template slot-scope="{ row }">
              <el-tag size="medium"
                :style="
                  row.deviceStatus | constantKeyTagStyleObj('WARNING_TYPE')
                ">
                {{ row.deviceStatus | constantKeyValue('WARNING_TYPE') }}
              </el-tag>
            </template>
          </af-table-column>
          <af-table-column align="center"
            label="告警状态"
            prop="solveStatus">
            <template slot-scope="{ row }">
              <el-tag size="medium"
                :style="
                  row.solveStatus | constantKeyTagStyleObj('HANDLE_STATUS')
                ">
                {{ row.solveStatus | constantKeyValue('HANDLE_STATUS') }}
              </el-tag>
            </template>
          </af-table-column>

          <af-table-column align="center"
            label="确认时间"
            prop="confirmTime">
            <template slot-scope="{ row }">
              {{ row.confirmTime | datefmt('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </af-table-column>

          <!-- <af-table-column align="center" label="确认人" prop="confirmUser" /> -->
          <af-table-column align="center"
            label="确认状态"
            prop="confirmRemark" />

          <af-table-column align="center"
            label="工单状态"
            prop="jobStatus">
            <template slot-scope="{ row }">
              <el-tag size="medium"
                :style="row.jobStatus | constantKeyTagStyleObj('ORDER_STATUS')">
                {{ row.jobStatus | constantKeyValue('ORDER_STATUS') }}
              </el-tag>
            </template>
          </af-table-column>

          <el-table-column align="center"
            label="操作"
            width="150"
            fixed="right">
            <template slot-scope="{ row }">
              <el-tooltip effect="dark"
                content="详情"
                placement="top-start">
                <i class="iconfont icon-chakanxiangqing2 i-detail"
                  @click="toDetail(row)" />
              </el-tooltip>

              <i class="iconfont icon-fengefu i-fengefu"
                v-if="row.solveStatus === 0 && row.jobStatus == 0" />

              <el-tooltip effect="dark"
                content="派发工单"
                placement="top-start">
                <i class="iconfont icon-bianji2 i-edit"
                  @click="toDistribute(row)"
                  v-if="row.solveStatus === 0 && row.jobStatus == 0" />
              </el-tooltip>
              <i class="iconfont icon-fengefu i-fengefu"
                v-if="!row.alarmJobCode && row.eliminateType !== 1" />

              <el-tooltip effect="dark"
                content="消除警报"
                placement="top-start">
                <img :src="eliminateIcon"
                  style="
                      position: relative;
                      width: 16px;
                      height: 16px;
                      top: 3px;
                      cursor: pointer;
                    "
                  @click="toEliminate(row)"
                  v-if="!row.alarmJobCode && row.eliminateType !== 1" />
              </el-tooltip>

              <i class="iconfont icon-fengefu i-fengefu" />

              <el-tooltip effect="dark"
                content="弹窗恢复"
                placement="top-start">
                <i class="iconfont icon-zujian-danchuang i-edit"
                  @click="toAlarmDialog(row)" />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0"
          :total="total"
          :page.sync="pagination.pageNum"
          :limit.sync="pagination.pageSize"
          :page-sizes="pageSizeOptions"
          @pagination="getDataList(true)" />
      </div>
    </el-card>

    <detail v-if="detailDialogObj.isVisible"
      ref="detailDialog"
      :dialog-visible="detailDialogObj.isVisible"
      :title="detailDialogObj.title"
      :params="params"
      @close="dialogClose('detailDialogObj')" />
    <eliminate-warning v-if="eliminateDialog.isVisible"
      ref="eliminateDialog"
      :alarm-reason-data="alarmReasonData"
      :dialog-visible="eliminateDialog.isVisible"
      :delete-id-str="deleteIdStr"
      @close="closeDialog()"
      @success="closeDialog()" />
    <distribute v-if="distributeDialog.isVisible"
      ref="distributeDialog"
      :params="distributeParams"
      :dialog-visible="distributeDialog.isVisible"
      :delete-id-str="deleteIdStr"
      @close="closeDialog()" />

    <AlarmDialog v-if="showWarnDialog"
      :visible="showWarnDialog"
      :systemMsg="warningObj"
      @close="onCloseWarningDialog"></AlarmDialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import dataTableMixins from '@/mixins/data-table-mixins'
import Detail from './components/detail.vue'
import eliminateWarning from './components/eliminateWarning.vue'
import Distribute from './components/distribute.vue'
import deviceManageApi from '@/api/device-manage'
import AlarmDialog from '@/components/AlarmDialog/index'
import warningManageApi from '@/api/warning-manage'

export default {
  name: 'DeviceList',
  components: {
    Pagination,
    Detail,
    eliminateWarning,
    Distribute,
    AlarmDialog,
  },
  mixins: [dataTableMixins],
  data () {
    return {
      eliminateIcon: require('@/assets/alarm_elimination.png'),
      eliminateIcon1: require('@/assets/alarm_elimination1.png'),
      searchArray: [],
      deleteLoading: false,
      popoverVisible: false,
      maxHeightDialog: '0px',
      eliminateDialog: {
        isVisible: false,
        title: '',
      },
      distributeDialog: {
        isVisible: false,
        title: '',
      },
      clickedDeviceLocation: '',
      clickedDeviceObj: {},
      deviceStatusList: [
        { label: '报警', value: 2 },
        { label: '故障', value: 1 },
        { label: '反馈', value: 3 },
        { label: '启动', value: 4 },
      ],
      solveStatusList: [
        { label: '未处理', value: 0 },
        { label: '已处理', value: 1 },
      ],
      jobStatusList: [
        { label: '未派单', value: 0 },
        { label: '待处理', value: 1 },
        { label: '已处理', value: 2 },
        // { label: '审核通过', value: 3 },
        // { label: '审核不通过', value: 4 },
      ],
      deviceIsLineList: [
        { label: '传统有线', value: 0 },
        { label: '智能无线', value: 1 },
      ],
      value: '',
      value2: '',
      pickerOptions: '',
      warningOptions: '',
      alarmReasonData: [],
      deleteIdStr: '',
      distributeParams: {},
      deviceDictionaries: [],

      warningObj: {}, //
      showWarnDialog: false,

      timeId: null,
    }
  },
  computed: {
    refreshWarningList () {
      return this.$store.state.global.refreshWarningList
    },
  },
  watch: {
    refreshWarningList: {
      handler (e) {
        this.getDataList(false)
      },
    },
  },

  beforeRouteLeave (to, from, next) {
    clearInterval(this.timeId)
    this.timeId = null
    next()
  },
  created () {
    // this.timeId = setInterval(() => {
    //   this.getDataList(false)
    // }, 10 * 1000)
  },
  mounted () {
    this.getDictValueAttr()
    // this.getDataList()
    this.getAlarmType()
  },
  methods: {
    isChecked (row, index) {
      if (row.alarmJobCode || row.eliminateType === 1) {
        return false
      }
      return true
    },
    getDictValueAttr () {
      const data = {
        fieldName: 'collect_type',
        tableName: 't_equipment_collect',
      }
      deviceManageApi.getDictValueAttr(data).then((ret) => {
        this.deviceDictionaries = ret.data.dictValue
        this.getDataList(true)
      })
    },
    getDataList (bool) {
      if (bool) {
        this.loading = true
      }

      const searchModel = this.formatSearchData(this.searchModel)
      warningManageApi
        .getEquipmentCollectAlertList({
          ...this.pagination,
          ...searchModel,
          ...this.sort,
        })
        .then((ret) => {
          this.dataList = ret.data.data.rows
          // this.dataList.forEach((ele, i) => {
          //   this.selectedDataList.forEach((multEle, j) => {
          //     if (this.dataList[i].id === this.selectedDataList[j].id) {
          //       this.$refs.elTable.toggleRowSelection(this.dataList[i], true)
          //     }
          //   })
          // })
          this.dataList.forEach((ele, i) => {
            this.deviceDictionaries.forEach((ele1, i1) => {
              if (Number(ele.deviceType) === ele1.dictValue) {
                ele.deviceTypeStr = ele1.dictText
              }
            })
          })
          this.total = ret.data.data.total
          this.loading = false
        })
        .catch(() => {
          this.loading = false
          this.dataList = []
          this.total = 0
        })
    },
    toSearch () {
      this.pagination.pageNum = 1
      this.getDataList(true)
    },
    toReset () {
      this.searchModel = {}
      this.sort = {}
      this.$refs.elTable.clearSort()
      this.$refs.elTable.clearFilter()
      this.$refs.elTable.clearSelection()
      this.selectedDataList = []
      this.value = ''
      this.value2 = ''
      this.toSearch()
    },
    onSortChange (val) {
      console.log(val)
      this.sort.field = val.prop
      this.sort.order = val.order
      this.toSearch()
    },
    onSelectionChange (selection) {
      this.selectedDataList = selection
    },
    toEmptySelection () {
      this.$refs.elTable.clearSelection()
    },
    indexMethod (index) {
      return this.formatIndex(index, this.pagination)
    },
    toEliminate (data) {
      this.deleteIdStr = data.id + ''
      this.eliminateDialog.isVisible = true
    },
    toDistribute (data) {
      this.distributeParams = data
      this.deleteIdStr = []
      this.distributeDialog.isVisible = true
    },
    toDetail (data) {
      this.params = {
        ...data,
      }
      this.detailDialogObj.title = '告警记录 ＞详情'
      this.detailDialogObj.isVisible = true
    },
    handleDateChange (value) {
      if (value) {
        this.searchModel.alertTimeFrom = this.$moment(value[0]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        this.searchModel.alertTimeTo = this.$moment(value[1]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
      } else {
        this.searchModel.alertTimeFrom = ''
        this.searchModel.alertTimeTo = ''
      }
    },
    handleAuditDateChange (value) {
      if (value) {
        this.searchModel.auditTimeFrom = this.$moment(value[0]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        this.searchModel.auditTimeTo = this.$moment(value[1]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
      } else {
        this.searchModel.auditTimeFrom = ''
        this.searchModel.auditTimeTo = ''
      }
    },
    getAlarmType () {
      const data = {
        fieldName: 'alarm_actual_desc_2',
        tableName: 't_job_reply',
      }
      deviceManageApi.getDictValueAttr(data).then((r) => {
        this.alarmReasonData = r.data.dictValue
      })
    },
    batchComfirm () {
      if (!this.selectedDataList.length) {
        this.$message.warning('请勾选批量确认的数据')
        return false
      }
      const deleteIdStr = this.selectedDataList.map((el) => {
        return el.id
      })
      warningManageApi
        .confirmAlertTime({
          alertId: deleteIdStr,
        })
        .then((r) => {
          this.$message({
            message: '已确认',
            type: 'success',
          })
          this.toReset()
        })
    },
    batchEliminate () {
      if (!this.selectedDataList.length) {
        this.$message.warning('请勾选批量消警的数据')
        return false
      }
      this.deleteIdStr = this.selectedDataList
        .map((el) => {
          return el.id
        })
        .toString()
      this.eliminateDialog.isVisible = true
    },
    batchDistribution () {
      if (!this.selectedDataList.length) {
        this.$message.warning('请勾选批量派发的数据')
        return false
      }
      const deleteIdStr = this.selectedDataList.map((el) => {
        return el.id
      })
      this.deleteIdStr = deleteIdStr
      this.distributeDialog.isVisible = true
    },
    closeDialog () {
      this.eliminateDialog.isVisible = false
      this.distributeDialog.isVisible = false
      this.$refs.elTable.clearSelection()
      this.selectedDataList = []
      this.toSearch()
      // this.toReset()
    },

    toAlarmDialog (data) {
      this.warningObj = data
      this.showWarnDialog = true
    },
    onCloseWarningDialog () {
      this.showWarnDialog = false
      this.$store.commit('global/setRefreshWarningList', new Date())
    },
  },
}
</script>

<style lang="scss" scoped>
@import '../../../../styles/part-custom';
</style>
